<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 模型示例
 *
 * 这里继承了扩展后的核心模型基类
 */
class Province_model extends MY_Model {
	public function __construct(){
		$this->load->database();
	}

	public function get_all_items(){
		$where = array(
			'stutas' => 0
			);
		$result = $this->db->select('id, name, parentid')->where($where)->get('province')->result_array();
		$result = $this->format_province($result);
		return $result;
	}

	private function format_province($result){
		$tmp_arr = array();
		foreach ($result as $val) {
			$tmp_arr[$val['parentid']][$val['id']] = $val['name'];
		}
		return $tmp_arr;
	}

	public function getParentsCouple($area_id){
		$areas = getAreas();
		$crumbs = [];
		do{
			if (empty($areas[$area_id])){
				break;
			}
			$area = $areas[$area_id];
			$crumbs[$area_id] = $area['n'];
			if (empty($area['p'])){
				break;
			}
			$area_id = $area['p'];
		}while(true);
		return array_reverse($crumbs,true);
	}

	public function getAddress($area_name,$city)
    {
        //SELECT a.id,a.name,b.name FROM `province` a left join province b ON a.parentid = b.id where a.name='鼓楼区' and b.name='徐州市'
        $sql = "SELECT a.id,a.name,b.name as city FROM `province` a left join province b ON a.parentid = b.id where a.name='{$area_name}' and b.name='{$city}'";
        $result = $this->db->query($sql)->result_array();
        log_message('error','getAddress '.$result[0]['id']);
        if(count($result) == 1) {
            log_message('error','getAddress '.$area_name.' id '.$result[0]['id'].' ci '.$result[0]['city']);
            return $result[0]['id'];
        }
        return $area_name;
    }
}